package com.weiqiao.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.mall.domain.PageDecorationDetailEntity;
import com.weiqiao.mall.domain.PageDecorationEntity;
import com.weiqiao.mall.repository.IPageDecorationRepository;
import com.weiqiao.mall.service.IPageDecorationService;
import com.weiqiao.mall.service.vo.PageDecorationVO;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.PageUtil;
import com.weiqiao.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Pattern;

@Service("PageDecorationServiceImpl")
public class PageDecorationServiceImpl implements IPageDecorationService {

    @Autowired
    private IPageDecorationRepository pageDecorationRepository;

    @Override
    public Map getPageList(PageDecorationVO pageDecorationVO) {
        Document document = new Document();
        List<PageDecorationEntity> list = new ArrayList<>();
        Gson gson = new Gson();
        // 根据页面标题搜索
        if (!StringUtil.isBlank(pageDecorationVO.getPage_title())) {
            // 根据名字模糊查询
            Pattern pattern = Pattern.compile("^.*" + pageDecorationVO.getPage_title() + ".*$",
                    Pattern.CASE_INSENSITIVE);
            document.append("page_title", pattern);
        }
        document.append("company_id", pageDecorationVO.getCompany_id());
        document.append("is_del", 0);
        Document sort = new Document();
        sort.append("create_time", -1);
        // 分页查询
        List<String> pages = pageDecorationRepository.findAll(document, sort, pageDecorationVO.getPage(),
                pageDecorationVO.getSize());
        for (String page : pages) {
            list.add(gson.fromJson(page, PageDecorationEntity.class));
        }
        // 获取总条数
        int size = pageDecorationRepository.findAll(document).size();
        return PageUtil.toPage(list, size);
    }

    @Override
    public boolean deletePage(PageDecorationVO pageDecorationVO) {
        Document document = new Document();
        document.append("page_id", pageDecorationVO.getPage_id());
        document.append("company_id", pageDecorationVO.getCompany_id());
        PageDecorationEntity entity = this.findOne(document);
        if (StringUtil.isBlank(entity.getPage_id())) {
            return false;
        } else {
            entity.setIs_del(1);
            return pageDecorationRepository.updateOne(document, new Gson().toJson(entity));
        }
    }

    @Override
    public PageDecorationEntity findOne(Bson filter) {
        String one = pageDecorationRepository.findOne(filter);
        if (StringUtil.isBlank(one)) {
            return new PageDecorationEntity();
        }
        return new Gson().fromJson(one, PageDecorationEntity.class);
    }

    @Override
    public boolean updatePage(PageDecorationEntity pageDecorationEntity) {
        // 判断相对路径是否有重复
        Document pageDocument = new Document();
        pageDocument.append("company_id", pageDecorationEntity.getCompany_id());
        pageDocument.append("path", pageDecorationEntity.getPath());
        pageDocument.append("is_del", 0);
        pageDocument.append("page_id", new Document("$ne", pageDecorationEntity.getPage_id()));
        // 如果查询出数据则有重复
        String one = pageDecorationRepository.findOne(pageDocument);
        if (!StringUtil.isBlank(one)) {
            return false;
        }
        // 通过判断page_id判断新增还是修改
        if (StringUtil.isBlank(pageDecorationEntity.getPage_id())) {
            pageDecorationEntity.setPage_id(String.valueOf(System.currentTimeMillis()));
            pageDecorationEntity.setCreate_time(String.valueOf(System.currentTimeMillis()));
            pageDecorationEntity.setIs_del(0);
        }
        Document document = new Document();
        document.append("page_id", pageDecorationEntity.getPage_id());
        document.append("company_id", pageDecorationEntity.getCompany_id());
        return pageDecorationRepository.updateOne(document, new Gson().toJson(pageDecorationEntity));
    }

    /**
     * 获取页面装修首页列表
     *
     * @param request
     * @return
     */
    @Override
    public ResponseEntity getDecorationList(HttpServletRequest request, Pageable pageable) {
        int companyId = MallUtil.getCompanyId(request);
        Document document = new Document();
        document.append("company_id", companyId);
        //是否支持装修
        Integer is_decoration = MallUtil.getInteger(request, "is_decoration", null);
        if (is_decoration != null) {
            document.append("is_decoration", is_decoration);
        }
        //是否删除
        document.append("is_del", 0);
        String page_title = MallUtil.getString(request, "page_title", "");
        if (StringUtils.isNoneBlank(page_title)) {
            document.append("page_title", new Document("$regex", page_title));
        }
        // 获得总数
        int count = pageDecorationRepository.countNum(document);
        // 获取商城装修页面列表
        List<String> stringList = pageDecorationRepository.getPageDecorationList(document, pageable);
        List<PageDecorationEntity> resultList = new ArrayList<>();
        stringList.forEach(str -> resultList.add(new Gson().fromJson(str, PageDecorationEntity.class)));
        return new ResponseEntity(PageUtil.toPage(resultList, count), HttpStatus.OK);
    }

    /**
     * 获取页面装修-装修详情列表页
     *
     * @param request
     * @return
     */
    @Override
    public ResponseEntity getDecorationDetail(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        String pageId = MallUtil.getString(request, "page_id", "");
        Document document = new Document();
        document.append("company_id", companyId);
        document.append("page_id", pageId);
        List<String> stringList = pageDecorationRepository.getPageDecorationDetailList(document);
        List<PageDecorationDetailEntity> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(stringList)) {
            stringList.forEach(str -> resultList.add(new Gson().fromJson(str, PageDecorationDetailEntity.class)));
        }
        return new ResponseEntity(resultList, HttpStatus.OK);
    }

    /**
     * 批量发布
     *
     * @param request
     * @return
     */
    @Override
    public ResponseEntity saveDecorationDetail(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        String pageId = MallUtil.getString(request, "page_id", "");
        String deleteIds = MallUtil.getString(request, "del_ids", "");
        //先删除数据
        if (StringUtils.isNotBlank(deleteIds)) {
            List<String> delIdList = Arrays.asList(deleteIds.split(","));
            Document document = new Document();
            document.append("company_id", companyId);
            document.append("page_id", pageId);
            document.append("block_id", new Document("$in", delIdList));
            pageDecorationRepository.del(document);
        }
        Map<String, Object> resultMap = new HashMap<>(2);
        //获取需要发布的json数据集
        String jsonStr = MallUtil.getString(request, "page_detail", "");
        if (StringUtils.isNotBlank(jsonStr)) {
            List<PageDecorationDetailEntity> parseObject = JSON.parseArray(jsonStr, PageDecorationDetailEntity.class);
            if (CollectionUtils.isNotEmpty(parseObject)) {
                Predicate<String> predicate = str -> StringUtils.isBlank(str);
                parseObject.forEach(p -> {
                    //判断是新增还是修改
                    Document document = new Document();
                    document.append("company_id", companyId);
                    document.append("page_id", pageId);
                    document.append("block_id", p.getBlock_id());
                    document.append("navigation_type", p.getNavigation_type());
                    document.append("row_num", p.getRow_num());
                    String detail = pageDecorationRepository.getPageDecorationDetail(document);
                    pageDecorationRepository.findAndUpdate(document, Document.parse(new Gson().toJson(p)), predicate.test(detail));
                });
                resultMap.put("result", true);
                resultMap.put("msg", "发布成功");
                return new ResponseEntity(resultMap, HttpStatus.OK);
            }
        }
        resultMap.put("result", false);
        resultMap.put("msg", "没有数据需要发布");
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }
}
